<?php
namespace App\Http\Controllers\ApiWx;

use App\DBs\UploadDB;
use App\Utilitys\FFbase;
use App\Utilitys\Logs;
use App\Utilitys\Upload;
use Illuminate\Http\Request;

class UploadController extends BaseController
{
    //上传

    protected $db;
    protected $log;
    protected $ff;

    public function __construct()
    {
        parent::__construct();
        $this->db = new UploadDB();
        $this->log = new Logs();
        $this->ff = new FFbase();
    }

    /**
     * 上传
     */
    public function setUpload(Request $request)
    {
        ini_set("max_execution_time",0); //不限制执行的时间
        $this->log->setUpload('上传开始：-----');
        $this->log->setUpload($request->all());
        $wx = $request->post('wx','');
        $file = $request->file('file');
        $this->log->setUpload($file->getClientSize());
        $resPath = Upload::uploadFile($file);
        $this->log->setUpload($resPath);
        if ($resPath['code']!=0) {
            return array('code'=>'-5','msg'=>'upload false');
        }
        $filePath = $resPath['data']['filePath'];
        //视频宽高
        $this->log->setUpload('视频宽高');
        $resRadio = $this->ff->getVideoRadio($filePath);
        if ($resRadio['code']!=0) {
            return array('code'=>'-5','msg'=>'get w and h false');
        }
        $vw = $resRadio['w']; $vh = $resRadio['h'];
        //视频时长
        $this->log->setUpload('视频时长');
        $resDelay = $this->ff->getVideoDelay($filePath);
        if ($resDelay['code']!=0) {
            return array('code'=>'-5','msg'=>'get delay false');
        }
        $delay = $resDelay['data'];
        //视频封面
        $this->log->setUpload('视频封面');
        $resCover = $this->ff->getVideoCover($filePath,$delay,$vw,$vh);
        if ($resCover['code']!=0) {
            return array('code'=>'-5','msg'=>'get cover false');
        }
        $cover = $resCover['data'];
//        return [$filePath,$vw,$vh,$delay,$cover];
        //更新数据
        $this->log->setUpload('更新数据');
        $resDb = $this->db->setAdd($wx,$filePath,$cover,$vw,$vh,$delay);
        if ($resDb['code']!=0) {
            return $this->toWxJson(-500);
        }
        $items = [
            'link'=>env('DOMAIN').'/'.$filePath,
            'cover'=>env('DOMAIN').'/'.$cover,
            'vw'=>$vw, 'vh'=>$vh,
        ];
        $this->log->setUpload('上传结束：-----');
        return $this->toWxJson(0,$items);
    }
}